package com.fantasizegame.project.gen.utils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.fantasizegame.project.gen.entity.ColumnEntity;
import com.fantasizegame.project.gen.entity.TableEntity;

public class MysqlUtils {

	private static DruidDataSource ds = new DruidDataSource();
	static {

		Properties properties = new Properties();
		try {
			properties.load(new FileReader(new File(MysqlUtils.class.getClassLoader().getResource("db.properties").getFile())));
			ds.configFromPropeties(properties);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static List<TableEntity> getTables(String schema) throws SQLException {
		String				sql		= "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?";
		Connection			conn	= ds.getConnection();
		PreparedStatement	ps		= conn.prepareStatement(sql);

		ps.setString(1, schema);

		ResultSet			rs		= ps.executeQuery();

		List<TableEntity>	list	= new ArrayList<TableEntity>();
		while (rs.next()) {
			TableEntity entity = new TableEntity();
			entity.setTableName(rs.getString("TABLE_NAME"));
			list.add(entity);
		}
		return list;

	}

	public static TableEntity getColumns(String schema, TableEntity table) throws SQLException {

		String				sql		= "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_KEY,COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND  TABLE_NAME= ? ORDER BY ORDINAL_POSITION";
		Connection			conn	= ds.getConnection();
		PreparedStatement	ps		= conn.prepareStatement(sql);
		ps.setString(1, schema);
		ps.setString(2, table.getTableName());

		ResultSet			rs		= ps.executeQuery();

		List<ColumnEntity>	list	= new ArrayList<>();

		while (rs.next()) {

			ColumnEntity e = new ColumnEntity();
			e.setColumnName(rs.getString("COLUMN_NAME"));
			e.setType(rs.getString("DATA_TYPE"));
			e.setKey(rs.getString("COLUMN_KEY"));
			e.setDefaultValue(rs.getString("COLUMN_DEFAULT"));
			list.add(e);
		}
		table.setColumns(list);
		return table;

	}

}
